package cn.cxy.shapedemo

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.core.content.ContextCompat

fun View.setRoundRectStroke(colorStr: String, radiusInDp: Float, strokeWidth: Int) {
    setRoundRectStrokeByColorValue(Color.parseColor(colorStr), dp2px(context, radiusInDp), strokeWidth)
}

fun View.setRoundRectStroke(colorResId: Int, radiusInDp: Float, strokeWidth: Int) {
    setRoundRectStrokeByColorValue(ContextCompat.getColor(context, colorResId), dp2px(context, radiusInDp), strokeWidth)
}

fun View.setRoundRectStrokeByColorValue(color: Int, radius: Float, strokeWidth: Int) {
    val backgroundDrawable = GradientDrawable().also {
        it.shape = GradientDrawable.RECTANGLE
        it.cornerRadius = radius
        it.setStroke(strokeWidth, color)
    }
    background = backgroundDrawable
}

fun View.setRoundRectBg(colorStr: String, @DimenRes radiusDpResId: Int) {
    setRoundRectBgByColorValue(Color.parseColor(colorStr), dp(context, radiusDpResId))
}

fun View.setRoundRectBg(colorStr: String, radiusInDp: Float) {
    setRoundRectBgByColorValue(Color.parseColor(colorStr), dp2px(context, radiusInDp))
}

fun View.setRoundRectBg(@ColorRes colorResId: Int, @DimenRes radiusDpResId: Int) {
    setRoundRectBgByColorValue(ContextCompat.getColor(context, colorResId), dp(context, radiusDpResId))
}

fun View.setRoundRectBg(@ColorRes colorResId: Int, radiusInDp: Float) {
    setRoundRectBgByColorValue(ContextCompat.getColor(context, colorResId), dp2px(context, radiusInDp))
}

fun View.setRoundRectBgByColorValue(@ColorInt color: Int, radius: Float) {
    val backgroundDrawable = GradientDrawable().also {
        it.shape = GradientDrawable.RECTANGLE
        it.cornerRadius = radius
        it.setColor(color)
    }
    background = backgroundDrawable
}

private fun dp2px(context: Context, dpValue: Float) = TypedValue.applyDimension(1, dpValue, context.resources.displayMetrics)
private fun dp(context: Context, @DimenRes dpResId: Int) = context.resources.getDimension(dpResId)
